
import { Component } from 'react';
import { Layout, Card, Breadcrumb, Table, Space, Button, Tag, Form, Input, Modal, Popconfirm, Tree } from 'antd';
import axios from '@/utils/index.js';
const text = '确认删除本条角色信息?';
class Role extends Component {
  constructor() {
    super();
    this.state = {
      columns: [
        { title: '#', dataIndex: 'id', key: 'id' },
        { title: '角色名称', dataIndex: 'roleName', key: 'roleName' },
        { title: '角色描述', dataIndex: 'roleDesc', key: 'roleDesc' },
        {
          title: '操作',
          dataIndex: '',
          key: 'actions',
          render: (row, record) => (
            <Space>
              <Button type="primary" onClick={() => this.showeditModal(row, record.key)}>编辑</Button>
              <Popconfirm placement="top" title={text} onConfirm={() => this.delRole(row, record.key)} okText="确认删除" cancelText="不删除">
                <Button type="danger">删除角色</Button>
              </Popconfirm>
              <Button type="danger" onClick={() => this.showauthModal(row, record.key)}>分配权限</Button>
            </Space>
          )
        },
      ],
      data: [],
      editvisible: false,
      componentSize: 'Large',
      roleName: '',
      roleDesc: '',
      id: '',
      visible: false,
      authvisible: false,
      treeData: [],
      expandedKeys: ['0-0-0', '0-0-1'],
      checkedKeys: ['0-0-0'],
      selectedKeys: [],
      autoExpandParent: true
    }
  }
  onExpand = (expandedKeysValue) => {
    console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      autoExpandParent: false,
      expandedKeys: expandedKeysValue
    })
  };
  onCheck = (checkedKeysValue) => {
    console.log('onCheck', checkedKeysValue);
    this.setState({
      checkedKeys: checkedKeysValue
    })
  };
  onSelect = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    this.setState({
      selectedKeys: selectedKeysValue
    })
  };
  //初始化数据
  componentDidMount() {
    this.getRolelist();
    this.getAuthlist()
  }
  //对数据处理
  transformTree = (data) => {
    let obj = []
    return data.map(item => {
      obj = {
        title: item.authName,

        children: item.children && item.children.length > 0 ? item.children : [],
      }
      if (item.children && item.children.length > 0) {
        // console.log('@item.children', item.children);
        obj.children = this.transformTree(item.children)
      }
      return obj
    })
  };
  //获取权限列表
  getAuthlist = async () => {
    let result = await axios.get('/rights/tree')
    this.setState({
      treeData: this.transformTree(result.data.data)
    })
  }
  //获取角色列表
  getRolelist = async () => {
    let res = await axios.get('/roles')
    console.log(res);
    this.setState({
      data: res.data.data
    })
  }
  //打开编辑窗口
  showeditModal = (row, key) => {
    console.log(key);
    this.setState({
      editvisible: true,
      roleName: row.roleName,
      roleDesc: row.roleDesc,
      id: row.id
    })
  }
  //关闭修改用户对话框
  hideeditModal = () => {
    this.setState({
      editvisible: false,
    });
  }
  //修改角色
  editRole = async () => {
    let res = await axios.put('/roles/' + this.state.id, { roleName: this.state.roleName, roleDesc: this.state.roleDesc })
    console.log(res);
    this.setState({
      editvisible: false
    })
    this.getRolelist()
  }
  //删除角色
  delRole = async (row, key) => {
    console.log(key);
    let res = await axios.delete('/roles/' + row.id)
    console.log(res);
    this.getRolelist()
  }
  //打开添加角色窗口
  showaddModal = () => {
    this.setState({
      visible: true
    })
  }
  //关闭添加角色窗口
  hideaddModal = () => {
    this.setState({
      visible: false
    })
  }
  //添加角色信息
  addRole = async () => {
    let res = await axios.post('/roles', { roleName: this.state.roleName, roleDesc: this.state.roleDesc })
    console.log(res);
    this.setState({
      visible: false
    })
    this.getRolelist()
  }
  //添加权限对话框
  showauthModal = (row, key) => {
    console.log(key);
    this.setState({
      authvisible: true,
      id: row.id
    })
  }
  //关闭权限对话框
  hideauthModal = () => {
    this.setState({
      authvisible: false
    })
  }
  //添加权限
  addAuth = async () => {
    let res = await axios.post(`roles/${this.state.id}/rights`, { rids: this.state.selectedKeys })
    console.log(res);
  }
  render() {
    return (
      <Layout>
        <Card>
          <Breadcrumb style={{ margin: '5px 0', marginBottom: "10px" }}>
            <Breadcrumb.Item href="home">主页</Breadcrumb.Item>
            <Breadcrumb.Item href="role">角色</Breadcrumb.Item>
            <Breadcrumb.Item href="/home/role">列表</Breadcrumb.Item>
          </Breadcrumb>
          <Button type='primary' onClick={this.showaddModal}>添加角色</Button>
          <Table bordered style={{ marginTop: "20px", marginBottom: "15px" }}
            columns={this.state.columns}
            expandable={{ expandedRowRender: record => <Tag closable color="orange" style={{ margin: 0 }}>{record.children.authName}</Tag>, }}
            dataSource={this.state.data}
            rowKey="id"
            pagination={false} />
          {/* pagination={{ pagesize: 10 }} scroll={{ y: 15 }} */}


          {/* 添加角色对话框 */}
          <Modal title="添加角色信息"
            visible={this.state.visible}
            onOk={this.addRole} onCancel={this.hideaddModal} okText="确认" cancelText="取消">
            <Form
              labelCol={{ span: 4, }}
              wrapperCol={{ span: 14, }}
              layout="horizontal"
              size={this.state.componentSize}>
              <Form.Item label="角色名称">
                <Input value={this.state.roleName} onChange={e => { this.setState({ roleName: e.target.value }); }} />
              </Form.Item>
              <Form.Item label="角色描述">
                <Input value={this.state.roleDesc} onChange={e => { this.setState({ roleDesc: e.target.value }); }} />
              </Form.Item>
            </Form>
          </Modal>

          {/* 编辑角色对话框 */}
          <Modal title="修改角色"
            visible={this.state.editvisible}
            onOk={this.editRole} onCancel={this.hideeditModal} okText="确认" cancelText="取消">
            <Form
              labelCol={{ span: 4, }}
              wrapperCol={{ span: 14, }}
              layout="horizontal"
              size={this.state.componentSize}>
              <Form.Item label="角色名称">
                <Input value={this.state.roleName} onChange={e => { this.setState({ roleName: e.target.value }); }} />
              </Form.Item>
              <Form.Item label="角色描述">
                <Input value={this.state.roleDesc} onChange={e => { this.setState({ roleDesc: e.target.value }); }} />
              </Form.Item>
            </Form>
          </Modal>

          {/* 分配权限对话框 */}
          <Modal title="添加角色信息"
            visible={this.state.authvisible}
            onOk={this.addAuth} onCancel={this.hideauthModal} okText="确认" cancelText="取消">
            <Tree
              draggable
              checkable
              onExpand={this.onExpand}
              expandedKeys={this.state.expandedKeys}
              autoExpandParent={this.state.autoExpandParent}
              onCheck={this.onCheck}
              checkedKeys={this.state.checkedKeys}
              onSelect={this.onSelect}
              selectedKeys={this.state.selectedKeys}
              treeData={this.state.treeData}
            >
            </Tree>
          </Modal>
        </Card>
      </Layout>
    );
  }
}
export default Role;